package com.zmc.lostfound.gateway.service;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zmc.lostfound.common.dto.RoleAndPermissionDTO;
import com.zmc.lostfound.common.feign.AuthFeign;
import com.zmc.lostfound.common.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.zmc.lostfound.common.constant.RedisConstant.CACHE_ROLE_PERMISSION_KEY_PREFIX;

/**
 * @author zmc
 * @description 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    private final AuthFeign authFeign;

    private final StringRedisTemplate stringRedisTemplate;

    public StpInterfaceImpl(AuthFeign authFeign, StringRedisTemplate stringRedisTemplate) {
        this.authFeign = authFeign;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        Long userId = Long.valueOf(loginId.toString());
        RoleAndPermissionDTO roleAndPermissionDTO;
        String json = stringRedisTemplate.opsForValue().get(CACHE_ROLE_PERMISSION_KEY_PREFIX + userId);
        if (StrUtil.isNotBlank(json)) {
            roleAndPermissionDTO = JSONUtil.toBean(json, RoleAndPermissionDTO.class);
        } else {
            Result result = authFeign.queryRoleAndPermissionById(userId);
            roleAndPermissionDTO = result.getBean("roleAndPermissionDTO", RoleAndPermissionDTO.class);
        }
        return roleAndPermissionDTO.getPermissionCodeList();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        Long userId = Long.valueOf(loginId.toString());
        RoleAndPermissionDTO roleAndPermissionDTO;
        String json = stringRedisTemplate.opsForValue().get(CACHE_ROLE_PERMISSION_KEY_PREFIX + userId);
        if (StrUtil.isNotBlank(json)) {
            roleAndPermissionDTO = JSONUtil.toBean(json, RoleAndPermissionDTO.class);
        } else {
            Result result = authFeign.queryRoleAndPermissionById(userId);
            roleAndPermissionDTO = result.getBean("roleAndPermissionDTO", RoleAndPermissionDTO.class);
        }
        return roleAndPermissionDTO.getRoleCodeList();
    }

}
